import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class ElevatorManager {
    private final List<Elevator> elevators;
    private final Queue<Request> requestQueue;

    public ElevatorManager(int elevatorCount) {
        elevators = new ArrayList<>();
        requestQueue = new LinkedList<>();
        for (int i = 0; i < elevatorCount; i++) {
            elevators.add(new Elevator(i));
        }
    }

    public void addRequest(Request request) {
        requestQueue.add(request);
    }

    public void dispatch() {
        while (!requestQueue.isEmpty()) {
            Request request = requestQueue.poll();
            Elevator bestElevator = findBestElevator(request);
            if (bestElevator != null) {
                bestElevator.addTarget(request.getFromFloor());
                bestElevator.addTarget(request.getToFloor());
                System.out.println("Dispatching elevator " + bestElevator.getId()
                        + " to handle request from floor " + request.getFromFloor()
                        + " to floor " + request.getToFloor());
            }
        }

        for (Elevator elevator : elevators) {
            elevator.move();
        }
    }

    private Elevator findBestElevator(Request request) {
        Elevator selected = null;
        int minDistance = Integer.MAX_VALUE;

        for (Elevator elevator : elevators) {
            if (elevator.isIdle()) {
                int distance = Math.abs(elevator.getCurrentFloor() - request.getFromFloor());
                if (distance < minDistance) {
                    minDistance = distance;
                    selected = elevator;
                }
            }
        }

        return selected;
    }
}
